package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.IpUtil;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.entity.Button;
import com.antdesignbackend.backend.entity.Images;
import com.antdesignbackend.backend.entity.entityVo.RoomVo;
import com.antdesignbackend.backend.entity.Room;
import com.antdesignbackend.backend.entity.Shop;
import com.antdesignbackend.backend.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/room")
public class RoomController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    ReturnVO result = new ReturnVO();
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private Date createTime=new Date();
    private Integer menuId;
    private Integer userId;
    private Integer userType;
    private String roleID;
    @Autowired
    private IShopService shopService;
    @Autowired
    private UserService userService;
    @Autowired
    private IRoomService roomService;
    @Autowired
    private IImagesService imagesService;
    @Autowired
    private IAppointmentService appointmentService;
    @Autowired
    PermissionService permissionService;
    @Autowired
    ILogService logService;
    /**
     * 房间首页
     */
    @GetMapping("/index")
    @AuthToken
    public String index(String menuId,HttpServletRequest request) {
        this.menuId = Integer.parseInt(menuId);
        //获取cookies信息 roleID 1超级管理员，2管理员，3商户
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        return "room/index";

    }

    /**
     * 权限查询
     */
    @GetMapping("/getPermission")
    @AuthToken
    @ResponseBody
    public List<Button> permission(HttpServletRequest request) {
        if (request.getSession().getAttribute("RoleID") != null) {
            roleID = request.getSession().getAttribute("RoleID").toString();
        }
        //得到当前菜单具备的功能权限
        List<Button> list = permissionService.filterPermission(String.valueOf(roleID), menuId);
        return list;
    }


    /***
     * 前端分页查询
     *
     * @return
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    @PostMapping("/tableSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearch(@RequestBody RoomVo data,HttpServletRequest request) throws NoSuchMethodException, SecurityException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        System.out.println("进入房间管理");
        result = new ReturnVO();
        List<RoomVo> datalist=new ArrayList<>();
        QueryWrapper<RoomVo> wrapper =new QueryWrapper<RoomVo>();
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        //根据权限生成过滤条件
        if(roleID.equals("1") || roleID.equals("2"))
        {//管理员
        }
        else if(roleID.equals("3"))
        {
            wrapper.inSql("t.userId","select userid from users where Activity=1 and (UserID="+userId+" or parentID="+userId+")");
        }
        else
        {
            //否则不给数据
            wrapper.eq("userId",0);
        }
        //正常查询过滤条件
        if(data.getId()!=null && !data.getId().equals(""))
        {
            wrapper.eq("id",data.getId());
        }

        if(data.getState()!=null && !data.getState().equals(""))
        {
            wrapper.eq("state",data.getState());
        }
        if(data.getShopId()!=null && !data.getShopId().equals(""))
        {
            wrapper.eq("shopId",data.getShopId());
        }
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=roomService.count(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0)
        {
            datalist= roomService.search(wrapper.orderByAsc("name"),new Page<>(data.getPageIndex(),data.getPageSize()));
            if (datalist.size() > 0){
                for (RoomVo roomVo:datalist){
                    if (roomVo.getUrl() != null && !roomVo.getUrl().equals("")){
                        roomVo.setUrl(WebConfig.host+"/images/"+roomVo.getUrl());
                    }
                }
            }
            //得到当前菜单具备的功能权限
//            List<Button> list = permissionService.filterPermission(String.valueOf(roleID), menuId);
//            datalist.forEach(model -> model.setButtonList(list));
        }
        result.setData(datalist);
        return result;
    }
    /***
     * 新增/修改保存
     * id 0是新增加，否则修改
     * @return
     */
    @PostMapping("/save")
    @ResponseBody
    @AuthToken
    public ReturnVO save(@RequestBody RoomVo vo,HttpServletRequest request) throws Exception {
        result = new ReturnVO();
        boolean b = false;
        Room entity = new Room();
        if(vo.getId()>0)
        {
            //先获取旧的数据集
            entity= roomService.getById(vo.getId());
        }


        if(vo.getAction().equals("change"))
        {
            entity.setState(vo.getState());
        }
        else {
            //新增，修改
            entity.setName(vo.getName());
            entity.setShopId(vo.getShopId());
            entity.setPrice(vo.getPrice());
            entity.setMaxPerson(vo.getMaxPerson());
            entity.setMinPerson(vo.getMinPerson());
            entity.setTopic(vo.getTopic());
            entity.setRemark(vo.getRemark());
            entity.setState(vo.getState());
            entity.setIsMeter(vo.getIsMeter());
            entity.setRoomType(vo.getRoomType());
            entity.setInstructions(vo.getInstructions());
            entity.setSpace(vo.getSpace());
        }
        if (vo.getId() == 0) {
            //新增
           entity.setPraise(0);
            entity.setSaleTotal(0);
            b = roomService.save(entity);
        }else{
            //修改
            b = roomService.updateById(entity);
        }
        if(b==true){
            result.setMessage("保存成功！");
            result.setCode("200");
            String loginName=request.getSession().getAttribute("LoginName").toString();
            String ipaddress = IpUtil.getRemoteIp(request);
            logService.WriteLog(103, entity.toString()+"ip:"+ipaddress, loginName);
        }else{
            result.setMessage("保存失败！");
            result.setCode("500");
        }
        return result;
    }
    /**
     * 获得商户的店铺
     */
    @ResponseBody
    @GetMapping(value = "/getShopForRole")
    @AuthToken
    public ReturnVO getShopForRole(HttpServletRequest request) {
        result = new ReturnVO();
        QueryWrapper<Shop> wrapper =new QueryWrapper<Shop>();
        int userId=(int) request.getSession().getAttribute("UserID");
        String roleID=(String) request.getSession().getAttribute("RoleID");
        if(roleID.equals("1") || roleID.equals("2"))
        {//管理员
        }
        else if(roleID.equals("3"))
        {
            wrapper.inSql("userId","select userid from users where Activity=1 and (UserID="+userId+" or parentID="+userId+")");
        }
        else
        {
            //否则不给数据
            wrapper.eq("userId",0);
        }

        wrapper.eq("state",1);

        List<Shop> dataList = shopService.getBaseMapper().selectList(wrapper);
        result.setData(dataList);
        // logger.info("succ");
        return result;
    }
    /**
     * 根据商铺ID获得所有房间
     */
    @GetMapping("/getRoomName/{shopId}")
    @ResponseBody
        public ReturnVO getRoomName(@PathVariable int shopId){
        result=new ReturnVO();
        QueryWrapper<Room> queryWrapper=new QueryWrapper();
        queryWrapper.eq("shopId",shopId);
        List<Room> rooms=roomService.list(queryWrapper);
        result.setData(rooms);
        return  result;
    }
    /***
     * 上传图片
     * @return
     */
    @PostMapping("/uploadImages")
    @ResponseBody
    public String uploadImage(Integer type,Integer id,HttpServletRequest request) throws Exception {
        Map<String,String> result=new HashMap<>();
        long random =System.currentTimeMillis();
        String dateKey =random+"";
        String localPathDir="";
        String newFileName="";
        if(!WebConfig.uploadImage.equals(""))
        {
            localPathDir=WebConfig.uploadImage;
        }
        else
        {
            localPathDir= ResourceUtils.getURL("classpath:").getPath()+"images/";
        }
        //System.out.println("localPathDir:"+localPathDir);
        //  localPathDir="/usr/uploadFile/alipayfile/";
        //String localPathDir = "c:\\alipay";

        File logoSaveFile = new File(localPathDir);
        if(!logoSaveFile.exists()){
            logoSaveFile.mkdirs();
        }
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
            Iterator iter = mr.getFileMap().values().iterator();
            if (iter.hasNext()) {
                MultipartFile file = (MultipartFile) iter.next();
                String oname = file.getOriginalFilename();
                String fileTyle=oname.substring(oname.lastIndexOf("."),oname.length());
                fileTyle=fileTyle.toLowerCase();
                newFileName=dateKey+fileTyle;
                String fileName = localPathDir+newFileName;
                if(fileTyle.equals(".png") || fileTyle.equals(".gif") || fileTyle.equals(".jpg"))
                {
                    File files = new File(fileName);
                    InputStream inputstream =file.getInputStream();
                    byte[] bytes = new byte[1024];
                    FileOutputStream outstream = new FileOutputStream(fileName);
                    int index;
                    while ((index = inputstream.read(bytes)) != -1) {
                        outstream.write(bytes, 0, index);
                        outstream.flush();
                    }
                    outstream.close();
                    inputstream.close();
                }



            }
        }
         if(newFileName!=null && !newFileName.equals(""))
         {
             Images entity=new Images();
             if(type==1)
             {
                 QueryWrapper<Images> wrapper=new QueryWrapper<Images>();
                 wrapper.eq("type",1);
                 wrapper.eq("pid",id);
                 entity=imagesService.getOne(wrapper);
                 if(entity!=null)
                 {
                     entity.setUrl(newFileName);
                     imagesService.updateById(entity);
                 }
                 else
                 {
                     entity=new Images();
                      entity.setListorder(0.0);
                     entity.setPid(id);
                     entity.setType(type);
                     entity.setUrl(newFileName);
                     imagesService.save(entity);
                 }

             }
             else
             {
                 entity.setListorder(0.0);
                 entity.setPid(id);
                 entity.setType(type);
                 entity.setUrl(newFileName);
                 imagesService.save(entity);
             }


         }
        // System.out.println("return:"+localPathDir+newFileName);
        return newFileName;
    }
    /***
     * 获取房间图片
     * @return
     */
    @GetMapping("/getRoomImages")
    @ResponseBody
    public List<Object>  getRoomImages(Integer type,Integer roomId) throws Exception {
        List<Object> result=new ArrayList<>();

           QueryWrapper<Images> wrapper=new QueryWrapper<Images>();
           wrapper.eq("type",type);
           wrapper.eq("pid",roomId);

         List<Images> datalist=imagesService.list(wrapper);
         if(datalist.size()>0)
         {
             for (Images item: datalist ) {
                 Map<String,Object> data=new HashMap<>();
                 data.put("id",item.getId());
                 data.put("url",item.getUrl());
                 result.add(data);
             }
         }

        return result;
    }
    /***
     * 根据id删除图片
     */
    @DeleteMapping("/deleteImageById/{id}")
    @ResponseBody
    public ReturnVO deleteImageById(@PathVariable Serializable id) {
        result = new ReturnVO();
        if (imagesService.removeById(Integer.parseInt(id.toString())) == true) {
            result.setMessage("删除成功");
            result.setCode("200");
        } else {
            result.setMessage("删除失败");
            result.setCode("500");
        }
        return result;
    }
    /***
     * 根据id删除
     */
    @DeleteMapping("/deleteById/{id}")
    @ResponseBody
    public ReturnVO deleteById(@PathVariable Serializable id) {
        result = new ReturnVO();
        if (roomService.removeById(Integer.parseInt(id.toString())) == true) {
            result.setMessage("删除成功");
            result.setCode("200");
        } else {
            result.setMessage("删除失败");
            result.setCode("500");
        }
        return result;
    }
    /***
     * 人工预约查询
     * @return
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    @PostMapping("/roomSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO roomSearch(@RequestBody RoomVo data,HttpServletRequest request) throws NoSuchMethodException, SecurityException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        result = new ReturnVO();
        List<RoomVo> datalist=new ArrayList<>();
        List<RoomVo> roomlist=new ArrayList<>();
        QueryWrapper<RoomVo> wrapper =new QueryWrapper<RoomVo>();
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        //根据权限生成过滤条件
        if(roleID.equals("1")){//管理员
        }else{
            wrapper.inSql("t.userId","select userid from users where Activity=1 and (UserID="+userId+" or parentID="+userId+")");
        }
        //正常查询过滤条件
        if(data.getShopName()!=null && !data.getShopName().equals(""))
        {
            wrapper.and(wra -> wra.like("s.Name", data.getShopName()));
        }
        if(data.getAddress()!=null && !data.getAddress().equals(""))
        {
            wrapper.and(wra -> wra.like("address", data.getAddress()));
        }
        if(data.getShopType()!=null && !data.getShopType().equals(""))
        {
            wrapper.and(wra -> wra.like("shopType", data.getShopType()));
        }
        if(data.getProvinceCode()!=null && !data.getProvinceCode().equals(""))
        {
            wrapper.eq("s.provinceCode", data.getProvinceCode());
        }
        if(data.getCityCode()!=null && !data.getCityCode().equals(""))
        {
            wrapper.eq("s.cityCode", data.getCityCode());
        }
        if(data.getAreaCode()!=null && !data.getAreaCode().equals(""))
        {
            wrapper.eq("s.areaCode", data.getAreaCode());
        }
        wrapper.eq("t1.state", 1);
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=roomService.countRoom(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0)
        {
            datalist= roomService.searchRoom(wrapper.orderByAsc("name"),new Page<>(data.getPageIndex(),data.getPageSize()));
            //筛选可预约的房间
            if(data.getStartTime()!=null && !data.getStartTime().equals("") && data.getEndTime()!=null && !data.getEndTime().equals("")){
                for(RoomVo room:datalist){
                    Boolean b=appointmentService.IsAppoint(room.getId(),data.getStartTime(),data.getEndTime());
                    if(b){
                        roomlist.add(room);
                    }
                }
            }else {
                roomlist=datalist;
            }
        }
        result.setData(roomlist);
        return result;
    }

}
